package cn.tedu.blackhorse.filter;

import cn.tedu.blackhorse.ex.ServiceCode;
import cn.tedu.blackhorse.security.LoginPrincipal;
import cn.tedu.blackhorse.web.JsonResult;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import sun.rmi.runtime.Log;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    @Value("${BH.jwt.secret-key}")
    private String secretKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("处理JWT的过滤器开始执行...........");

        //清除SecurityContext中原有的认证信息
        //避免曾经成功访问过,后续不携带jwt也视为已认证
        SecurityContextHolder.clearContext();

        String jwt = request.getHeader("authorization");
        log.debug("尝试从请求头中获取jwt数据:{}",jwt);
        if (!StringUtils.hasText(jwt) || jwt.length()<113) {
            log.debug("过滤器执行[放行]");
            filterChain.doFilter(request, response);
            return;
        }

        log.debug("获取到的jwt被视为有效,则尝试分析....");


        Claims claims = null;
        response.setContentType("application/json; charset=utf-8");
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch(ExpiredJwtException e){
            log.debug("解析失败:{}:{}",e.getClass().getName(),e.getMessage());
            Integer serviceCode = ServiceCode.ERR_JWT_EXPIRED.getValue();
            String message= "用户登录已过期,请重新登录";
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode,message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            writer.close();
            return;
        }catch(SignatureException e){
            log.debug("解析失败:{}:{}",e.getClass().getName(),e.getMessage());
            Integer serviceCode = ServiceCode.ERR_JWT_EXPIRED.getValue();
            String message= "用户登录已过期,请重新登录";
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode,message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            writer.close();
            return;
        }catch(MalformedJwtException e){
            log.debug("解析失败:{}:{}",e.getClass().getName(),e.getMessage());
            Integer serviceCode = ServiceCode.ERR_JWT_EXPIRED.getValue();
            String message= "用户登录已过期,请重新登录";
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode,message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            writer.close();
            return;
        }catch(Throwable e){
            log.debug("解析失败:{}:{}",e.getClass().getName(),e.getMessage());
            Integer serviceCode = ServiceCode.ERR_JWT_PARSE.getValue();
            String message= "用户登录已过期,请重新登录";
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode,message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            writer.close();
            return;
        }

        String username = claims.get("username", String.class);
        log.debug("从jwt中解析得到username的值为:{}",username);
        String authorityListString = claims.get("authorities", String.class);
        log.debug("从jwt中解析得到authorityListString的值为:{}",authorityListString);
        Long id = claims.get("id",Long.class);
        log.debug("从jwt中解析得到id={}",id);
        //准备权限,将全线封装到认证信息中
        List<SimpleGrantedAuthority> authorityList = JSON.parseArray(authorityListString, SimpleGrantedAuthority.class);
        log.debug("从jwt中解析得到authorityListString的值通过JSON的值为:{}",authorityList);

        // 创建自定义的当事人类型的对象
        LoginPrincipal loginPrincipal = new LoginPrincipal();
        loginPrincipal.setId(id);
        loginPrincipal.setUsername(username);

        //准备存入到SecurityContext的认证信息
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginPrincipal,null,authorityList);

        //将认证信息存入SercuityContext中
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        log.debug("过滤器执行[放行]");
        filterChain.doFilter(request, response);
    }
}
